#include "filterproxymodel.h"
#include "productlistmodel.h"
#include "purchasableitembase.h"

#include <QDebug>

// "items to buy" filter
ItemsToBuyModel::ItemsToBuyModel(QAbstractItemModel &sourceModel, QObject* parent):
    QSortFilterProxyModel(parent)
{
    setSourceModel(&sourceModel);
    setFilterRole(PurchasableItemBase::IsActivated);
}

bool ItemsToBuyModel::filterAcceptsRow(int sourceRow, const QModelIndex & sourceParent) const
{
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
    return (!sourceModel()->data(index, PurchasableItemBase::IsActivated).toBool());
}

// "items you have" filter
ItemsYouHaveModel::ItemsYouHaveModel(QAbstractItemModel &sourceModel, QObject* parent):
    ItemsToBuyModel(sourceModel, parent)
{
}

bool ItemsYouHaveModel::filterAcceptsRow(int sourceRow, const QModelIndex & sourceParent) const
{
    return (!ItemsToBuyModel::filterAcceptsRow(sourceRow, sourceParent));
}


FilterProxyModel::FilterProxyModel(QObject *parent):
    QSortFilterProxyModel(parent)
{
    setSourceModel(new ProductListModel(this));
    setDynamicSortFilter(false);
    sort(0);

    connect(sourceModel(), SIGNAL(applicationBusyChanged()), this, SLOT(modelBusyChanged()));
    connect(sourceModel(), SIGNAL(purchaseCompleted(bool)), this, SLOT(purchaseCompleted(bool)));
}

bool FilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    ProductListModel* model = qobject_cast<ProductListModel*>(sourceModel());
    //sort in activation order. Not purchased items go first
    PurchasableItemBase* dataLeft = model->record(left);
    PurchasableItemBase* dataRight = model->record(right);

    if (dataLeft && dataLeft->isActivated() && !(dataRight && dataRight->isActivated()))
        return false;

    return true;
}

void FilterProxyModel::modelUpdated()
{
    qDebug() << "model was re-sorted";
    sort(0);
}

void FilterProxyModel::buy(int idx)
{
    QModelIndex recIdx = mapToSource(index(idx, 0));

    qobject_cast<ProductListModel*>(sourceModel())->buy(recIdx);
}

void FilterProxyModel::restoreProducts()
{
    qobject_cast<ProductListModel*>(sourceModel())->restoreProducts();
}

void FilterProxyModel::getUserInfo()
{
    qobject_cast<ProductListModel*>(sourceModel())->getUserInfo();
}

bool FilterProxyModel::isApplicationBusy() const
{
    return qobject_cast<ProductListModel*>(sourceModel())->m_isApplicationBusy;
}

void FilterProxyModel::modelBusyChanged()
{
    emit applicationBusyChanged();
}

void FilterProxyModel::purchaseCompleted(bool status)
{
    emit appPurchaseCompleted(QVariant(status));
}

void FilterProxyModel::readDRMCatalog()
{
    qobject_cast<ProductListModel*>(sourceModel())->readDRMCatalog();
}

void FilterProxyModel::resetPurchases()
{
    qobject_cast<ProductListModel*>(sourceModel())->resetPurchases();
}

